package com.ygqh.baby.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import com.ygqh.baby.dao.GridFSDao;

@Component
public class GridFSUtil {
	
	@Autowired
	private GridFSDao gridFSDao;
	private static GridFSDao staticGridFSDao;
	

	@PostConstruct
	public void init(){
		GridFSUtil.staticGridFSDao = gridFSDao;
	}

	public static GridFSFile saveFile(File file, Boolean isDistinct){
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			String filename = file.getName();
			if (isDistinct) {
				
				return staticGridFSDao.storeUnique(fis, filename, FileUtil.getFileContentType(filename));
			}
			return staticGridFSDao.store(fis, filename, FileUtil.getFileContentType(filename));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally{
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static GridFSFile saveFile(MultipartFile file){
		try {
			return staticGridFSDao.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static GridFSFile saveFile(InputStream is,String fileName,String contentType){
		if(is!=null){
			return staticGridFSDao.store(is, fileName, contentType);
		}
		return null;
	}
	
	public static void deleteFileById(String id){
		staticGridFSDao.deleteById(id);
	}
	
	public static void deleteFileByNameAndType(String filename,String contentType){
		staticGridFSDao.delete(filename, contentType);
	}
	
	public static GridFSDBFile getFileById(String id){
		try {
			return staticGridFSDao.findById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static GridFSDBFile getOneFile(String filename,String contentType){
		try {
			return staticGridFSDao.findOne(filename, contentType);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
}
